<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属店铺">
        <el-input
          v-model="dianpumingcheng"
          placeholder="请输入店铺"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品ID" prop="spId">
        <el-input
          v-model="queryParams.spId"
          placeholder="请输入团购商品ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动名称">
        <el-input
          v-model="huodongmingcheng"
          placeholder="输入活动名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="活动开始">
        <el-date-picker
          v-model="time1"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="活动结束">
        <el-date-picker
          v-model="time2"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="活动创建">
        <el-date-picker
          v-model="time3"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="价格区间" label-width="100px" style="margin-right: 30px;">
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <el-input
            v-model="countmin"
            placeholder="请输入最小值"
            clearable
            @keyup.enter.native="handleQuery"
            style="flex: 1;width: 50px;margin-right: 10px;"
          />
          <el-input
            v-model="countmax"
            placeholder="请输入最大值"
            clearable
            @keyup.enter.native="handleQuery"
            style="flex: 1;"
          />
        </div>
      </el-form-item>

      <el-form-item label="售卖数量" style="display: flex; align-items: center;">
        <div style="display: flex; margin-right: 30px;">
          <el-input
            v-model="minyueshou"
            placeholder="请输入最小值"
            clearable
            @keyup.enter.native="handleQuery"
            style="flex: 1; margin-right: 10px;width: 50px"
          />
          <el-input
            v-model="maxyueshou"
            placeholder="请输入最大值"
            clearable
            @keyup.enter.native="handleQuery"
            style="flex: 1;"
          />
        </div>
      </el-form-item>

      <el-form-item label="审核状态" prop="sjtgZt">
        <el-select v-model="queryParams.sjtgZt" placeholder="请选择审核状态" clearable>
          <el-option
            v-for="dict in dict.type.shangjiatuangou"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:shangjiatuangou:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shangjiatuangouList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称"  width="170" align="center">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center;">
            <!-- 显示图片 -->
            <image-preview :src="scope.row.shangpin.spTupian" style="width: 30px; height: 30px; margin-right: 10px; margin-left: 20px"/>
            <!-- 包裹名字和ID的容器，使用Flex的列方向布局 -->
            <div style="display: flex; flex-direction: column; align-items: flex-start;">
              <!-- 显示商品名称 -->
              <span style="line-height: 30px;">{{ scope.row.shangpin.spName }}</span>
              <!-- 显示商品ID，通过margin-top调整位置以模拟底部对齐 -->
              <span style="margin-top: 2px;">ID:{{ scope.row.shangpin.spId }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="团购价" align="center">
        <template v-slot="scope">
          <div style="display: flex; flex-direction: column; align-items: flex-start; margin-left: 25px">
            <span style="color: black;">￥{{ scope.row.shangpin.spPianyi }}</span>
            <span style="color: gray; text-decoration: line-through; margin-top: 5px;">(原价: ￥{{ scope.row.shangpin.spJiage }})</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="shangpin.spKaishitime" />
      <el-table-column label="结束时间" align="center" prop="shangpin.spJieshutime" />
      <el-table-column label="已售数量" align="center" prop="shangpin.spYueshou" />
      <el-table-column label="所属店铺" align="center" prop="dianpu.dpName" />
      <el-table-column label="创建时间" align="center" prop="shangpin.spAddtime" />
      <el-table-column label="审核状态" align="center" prop="sjtgZt">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.shangjiatuangou" :value="scope.row.sjtgZt"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:shangjiatuangou:edit']"
          >审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商家团购活动对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="审核状态" prop="sjtgZt">
          <el-select v-model="form.sjtgZt" placeholder="请选择审核状态">
            <el-option
              v-for="dict in dict.type.shangjiatuangou"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listShangjiatuangou, getShangjiatuangou, delShangjiatuangou, addShangjiatuangou, updateShangjiatuangou } from "@/api/system/shangjiatuangou";

export default {
  name: "Shangjiatuangou",
  dicts: ['shangjiatuangou'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商家团购活动表格数据
      shangjiatuangouList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dianpumingcheng:null,
      huodongmingcheng:null,
      time1:'',
      time2:'',
      time3:'',
      countmin:null,
      countmax:null,
      minyueshou:null,
      maxyueshou:null,
      // 审核状态时间范围
      daterangeSjtgCreatetime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dpId: null,
        spId: null,
        sjtgCreatetime: null,
        sjtgZt: null,

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        dpId: [
          { required: true, message: "商家ID不能为空", trigger: "blur" }
        ],
        spId: [
          { required: true, message: "团购商品ID不能为空", trigger: "blur" }
        ],
        sjtgCreatetime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        sjtgZt: [
          { required: true, message: "审核状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询商家团购活动列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (this.dianpumingcheng != null && this.dianpumingcheng != ''){
        this.queryParams.params["dianpumingcheng"] = this.dianpumingcheng
      }
      if (this.huodongmingcheng != null && this.huodongmingcheng != ''){
        this.queryParams.params["huodongmingcheng"] = this.huodongmingcheng
      }
      if (null != this.time1 && '' != this.time1) {
        this.queryParams.params["beginStart"] = this.getGoodTime(this.time1[0]);
        this.queryParams.params["beginendStart"] = this.getGoodTime(this.time1[1]);
      }
      if (null != this.time2 && '' != this.time2) {
        this.queryParams.params["endStart"] = this.getGoodTime(this.time2[0]);
        this.queryParams.params["endderStart"] = this.getGoodTime(this.time2[1]);
      }
      if (null != this.time3 && '' != this.time3) {
        this.queryParams.params["beginchuangjianStart"] = this.getGoodTime(this.time3[0]);
        this.queryParams.params["endchuangjianStart"] = this.getGoodTime(this.time3[1]);
      }
      if (null != this.countmin && '' != this.countmin && null != this.countmax && '' != this.countmax){
        this.queryParams.params["minjiage"] = this.countmin;
        this.queryParams.params["maxjiage"] = this.countmax;
      }
      if (null != this.minyueshou && '' != this.minyueshou && null != this.maxyueshou && '' != this.maxyueshou){
        this.queryParams.params["minyueshou"] = this.minyueshou;
        this.queryParams.params["maxyueshou"] = this.maxyueshou;
      }
      listShangjiatuangou(this.queryParams).then(response => {
        this.shangjiatuangouList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      console.log(this.queryParams)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sjtgId: null,
        dpId: null,
        spId: null,
        sjtgCreatetime: null,
        sjtgZt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeSjtgCreatetime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sjtgId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商家团购活动";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const sjtgId = row.sjtgId || this.ids
      getShangjiatuangou(sjtgId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商家团购活动";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.sjtgId != null) {
            updateShangjiatuangou(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addShangjiatuangou(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sjtgIds = row.sjtgId || this.ids;
      this.$modal.confirm('是否确认删除商家团购活动编号为"' + sjtgIds + '"的数据项？').then(function() {
        return delShangjiatuangou(sjtgIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/shangjiatuangou/export', {
        ...this.queryParams
      }, `shangjiatuangou_${new Date().getTime()}.xlsx`)
    },

    //时间格式转化
    getGoodTime(time) {
      // 尝试将输入字符串解析为Date对象
      let date = new Date(time);
      // 检查Date对象是否有效（即不是Invalid Date）
      if (isNaN(date.getTime())) {
        throw new Error('Invalid date string');
      }
      // 提取年、月、日、时、分、秒
      // 月份从0开始，所以要加1；日期、小时、分钟、秒直接使用
      // 使用padStart来确保月份、日期、小时、分钟、秒始终是两位数
      const year = time.getFullYear();
      const month = String(time.getMonth() + 1).padStart(2, '0');
      const day = String(time.getDate()).padStart(2, '0');
      const hours = String(time.getHours()).padStart(2, '0');
      const minutes = String(time.getMinutes()).padStart(2, '0');
      const seconds = String(time.getSeconds()).padStart(2, '0');

      // 拼接成所需的格式
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
  }
};
</script>
